#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update:

'''绝对坐标, 全局的操作
'''

__revision__ = '0.1'
__author__ = 'lxd'
import time
import config

class Helper():
    def __init__(self,log,dm):
        self.log = log
        self.dm = dm

    def checkMainPage(self):
        if self.__checkGame():
            self.closeWidgets()
            self.__enterCity()
            self.__enterMainPage()
            return self.__getMainCityPos()
        return False

    def __checkGame(self):
        point = self.dm.findPic(r'static/user.bmp')
        if point:
            self.log.debug('find user bmp now')
            return True
        else:
            self.log.debug('no find user bmp')
            return False

    def closeWidgets(self):
        """关掉额外窗口
        """
        self.dm.clickIfFindMultiColor('fee19f,-2|-8|784238,3|3|f3e4c5', wait=True)
        self.dm.clickIfFindMultiColor('ffeaa8,-4|5|fff0c8,6|1|a34c43', wait=True)
        self.log.debug('close widget success')

    def __enterCity(self):
        """进城
        """
        if self.dm.clickIfFindPic(r'static/out.bmp', wait=True):
            self.log.debug('enter city sucess')
        else:
            self.log.debug('not need to enter city')

    def __enterMainPage(self):
        """进入主页面
        """
        color = self.dm.getColor(106, 80)
        if color != '006468' and color != '00f5fe':
            self.dm.click(123,84)
            self.log.debug('enter main page sucess')
        else:
            self.log.debug('not need to enter main page')

    def __getMainCityPos(self):
        """获得官府的坐标，作为主页面的原点
        """
        poses = self.getBuildsPos(u'官府')
        if poses:
            self.log.debug(u'主页面原点坐标（官府）:%s' %str(poses[0]))
        else:
            self.log.info(u'请确保鼠标在主城的主页面上，且不能有其他任何窗口')
        return poses[0]

    def getRank(self, point):
        """获得名字旁边的等级
        """
        x0, y0 = point[0] - 27, point[1] - 4
        x1, y1 = point[0] - 6, point[1] + 12
        rank =  self.dm.ocr(x0, y0, x1, y1)
        try:
            return int(rank)
        except ValueError:
            return False

    def getBuildsPos(self, build_str):
        """获得多个建筑物坐标
        """
        r = []
        poses = self.dm.findStrs(build_str)
        if poses:
            for pos in poses:
                rank = self.getRank(pos)
                if rank:
                    r.append(pos)
        return r

    def closeTipMsg(self):
        """关掉提示窗口, 直接按确定
        """
        pos = self.dm.findPic(r'static/error_tip.bmp')
        if pos:
            self = self.dm.click(pos)
        else:
            self.log.debug('cannot find tip msg')
        return pos

    def showTip(self):
        """如果没有城池动态则打开
        """
        if self.dm.findPic(r'static/tip.bmp') or \
        self.dm.findStr(u'当前没有建造中的建筑'):
            self.log.debug('have blank tip')
        else:
            point = self.dm.findPic(r'static/showtip.bmp')
            if point: self.dm.click(point)
            self.log.debug('show blank tip success')

    def findLoading(self):
        return self.dm.findStr(u'正在加载')
##########get center##########
    def clickAnswerModel(self):
        r = self.dm.clickIfFindMultiColor('00c5fb,1|10|00fdc7')
        if r:
            self.log.debug('find question people success')
        else:
            self.log.debug('can not find question people')
        return r

    def getQuestionCenterPos(self):
        pos = self.dm.findStr(u'智者')
        if pos:
            self.log.debug('question center pos:%s' %str(pos))
        else:
            self.log.error('can not find question center pos')
        return pos

    def getFarmCenterPos(self):
        pos = self.dm.findPic(r'static/farm.bmp')
        if pos:
            self.log.debug('farm center pos:%s' %str(pos))
        else:
            self.log.error('can not find farm center pos')
        return pos

##########click不相对官府静止的##########
    def clickFarmModel(self):
        self.dm.clickIfFindMultiColor('98966c,7|7|98871f,23|2|eee58b')
##########go to city##########
    def _checkEntered(self):
        """查看是否城池加载完毕
        """
        while self.dm.isColor(85,99, '000000'):
            time.sleep(1)

    def gotoMainCity(self):
        self.dm.click(122,89)
        self._checkEntered()

    def gotoFirstCity(self):
        if self.dm.clickIfNotColor(172,83,'141a18'):
            self._checkEntered()
            return True
        else:
            return False

    def gotoSecondCity(self):
        if self.dm.clickIfNotColor(206, 81,'141a18'):
            self._checkEntered()
            return True
        else:
            return False

    def gotoThirdCity(self):
        if self.dm.clickIfNotColor(247, 82,'141a18'):
            self._checkEntered()
            return True
        else:
            return False

    def gotoFourthCity(self):
        if self.dm.clickIfNotColor(284, 85,'141a18'):
            self._checkEntered()
            return True
        else:
            return False
##########get buildings##########
    def __findSomeBuilds(self, builds):
        """第一项作为中心, 返回一个页面范围内的建筑相对坐标
        """
        r = []
        center_poses = self.getBuildsPos(builds[0])
        if center_poses:
            center_pos = center_poses[0]
            for build in builds:
                build_pos = self.dm.findStrs(build)
                if build_pos:
                    for point in build_pos:
                        rank = self.getRank(point)
                        if rank:
                            #建筑物点击感应相对坐标
                            x = point[0]-center_pos[0]-23
                            y = point[1]-center_pos[1]+35
                            r.append([build, rank, (x, y)])
        return r


    def _addBuilds(self, existed_builds, builds):
        """如果该建筑物坐标不存在则加入
        """
        def notExist(pos, existed_poses):
            for existed_pos in existed_poses:
                if (-10 < existed_pos[0]-pos[0] < 10) and (-10 < existed_pos[1]-pos[1] < 10):
                    return False
            return True
        someBuilds = self.__findSomeBuilds(builds)
        r = []
        if existed_builds:
            r.extend(existed_builds)
            existed_poses = [b[2] for b in existed_builds]
            for b in someBuilds:
                if notExist(b[2], existed_poses):
                    r.append(b)
        else:
            r = someBuilds
        return r

    def getDragPos(self, center_pos):
        """ 由中心坐标得到拖拽点
        """
        pos = center_pos[0]-175, center_pos[1]+24
        self.log.debug('drag pos is %s' %str(pos))
        return pos

    def findBuilds(self, builds):
        """通过拖拽鼠标返回所有建筑物信息
        """
        def getDragPos(build_name):
            """ 由中心建筑名得到拖拽点
            """
            center_poses = self.getBuildsPos(build_name)
            if center_poses:
                return self.getDragPos(center_poses[0])
            return center_poses

        def getDragPosAndRealBuilds(builds):
            if len(builds) == 2:
                point = getDragPos(builds[0][0])
                if point:
                    r = builds[0]
                else:
                    point = getDragPos(builds[1][0])
                    r = builds[1]
            else:
                point = getDragPos(builds[0])
                r = builds
            return point, r

        point, builds = getDragPosAndRealBuilds(builds)
        r = []
        if point:
            self.dm.moveTo(point)
            color = 0
            while color != self.dm.getColor(point):
                color = self.dm.getColor(point)
                r = self._addBuilds(r, builds)
                self.dm.drag(-100, -100)
        return r

    def getCenterBuildAndPos(self):
        """得到中心建筑名称和坐标
        """
        center_builds = [config.main_builds[0], config.other_builds[0][0], config.other_builds[1][0]]
        self.log.debug(u'center_builds:%s' %str(center_builds))
        self.log.debug('flash hwnd:%s' %self.dm.hwnd)
        while 1:#必须找到
            for center_build in center_builds:
                poses = self.getBuildsPos(center_build)
                if poses:
                    pos = poses[0]
                    self.log.debug('center_build is %s, pos is %s' %(center_build, str(pos)))
                    return center_build, pos
            else:
                self.log.debug('can not find center build')

